<template>
  <div id="mapView" class="map-view">
    <!-- 图层控制面板 -->
    <div class="layer-control-panel">
      <el-card class="layer-card">
        <el-collapse v-model="activeCollapse">
          <el-collapse-item title="图层显示控制" name="layers">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-checkbox
                v-model="layerVisibility.highway"
                @change="toggleLayerVisibility('highway')"
                >高速公路</el-checkbox
              >
              <el-checkbox
                v-model="layerVisibility.entryPoint"
                @change="toggleLayerVisibility('entryPoint')"
                >高速公路进入点</el-checkbox
              >
              <el-checkbox
                v-model="layerVisibility.serviceArea"
                @change="toggleLayerVisibility('serviceArea')"
                >高速公路服务区</el-checkbox
              >
              <el-checkbox v-model="layerVisibility.sign" @change="toggleLayerVisibility('sign')"
                >标志牌</el-checkbox
              >
            </el-space>
          </el-collapse-item>
          <el-collapse-item title="标志牌搜索" name="signSearch">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-input v-model="signSearchText" placeholder="请输入标志牌内容关键词" clearable>
                <template #append>
                  <el-button @click="searchSignByContent">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </el-space>
          </el-collapse-item>
          <el-collapse-item title="风险分析" name="riskAnalysis">
            <el-space direction="vertical" alignment="stretch" size="small">
              <el-button type="primary" @click="startDrawAnalysisArea" :disabled="isDrawing">
                绘制分析区域
              </el-button>
              <el-button
                type="success"
                @click="performRiskAnalysis"
                :disabled="!analysisAreaGraphic"
              >
                执行风险分析
              </el-button>
              <el-button
                type="danger"
                @click="clearAnalysis"
                :disabled="!analysisAreaGraphic && !analysisResultsVisible"
              >
                清除分析
              </el-button>
            </el-space>
          </el-collapse-item>
        </el-collapse>
      </el-card>
    </div>

    <!-- 道路属性查看对话框 -->
    <el-dialog v-model="roadInfoVisible" title="道路信息" width="500px">
      <div v-if="selectedRoad">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="道路名称">{{
            selectedRoad.attributes.RoadName
          }}</el-descriptions-item>
          <el-descriptions-item label="起点">{{
            selectedRoad.attributes.StartPoint
          }}</el-descriptions-item>
          <el-descriptions-item label="终点">{{
            selectedRoad.attributes.EndPoint
          }}</el-descriptions-item>
          <el-descriptions-item label="车道数">{{
            selectedRoad.attributes.LaneCount
          }}</el-descriptions-item>
          <el-descriptions-item label="设计速度"
            >{{ selectedRoad.attributes.DesignSpeed }} km/h</el-descriptions-item
          >
          <el-descriptions-item label="开通日期">{{
            selectedRoad.attributes.OpenDate
          }}</el-descriptions-item>
          <el-descriptions-item label="行政区域">{{
            selectedRoad.attributes.AdminRegion
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="queryRoadSigns">查询这条道路上的标志牌</el-button>
          <el-button @click="roadInfoVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 进出口点属性查看对话框 -->
    <el-dialog v-model="entryPointInfoVisible" title="高速进出口信息" width="500px">
      <div v-if="selectedEntryPoint">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="进出口名称">{{
            selectedEntryPoint.attributes.EntranceName
          }}</el-descriptions-item>
          <el-descriptions-item label="进出口类型">{{
            selectedEntryPoint.attributes.EntranceType
          }}</el-descriptions-item>
          <el-descriptions-item label="所属道路">{{
            getRoadNameById(selectedEntryPoint.attributes.RoadID)
          }}</el-descriptions-item>
          <el-descriptions-item label="方向">{{
            selectedEntryPoint.attributes.Direction
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="entryPointInfoVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 服务区属性查看对话框 -->
    <el-dialog v-model="serviceAreaInfoVisible" title="高速服务区信息" width="500px">
      <div v-if="selectedServiceArea">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="服务区名称">{{
            selectedServiceArea.attributes.AreaName
          }}</el-descriptions-item>
          <el-descriptions-item label="服务区类型">{{
            selectedServiceArea.attributes.AreaType
          }}</el-descriptions-item>
          <el-descriptions-item label="所属道路">{{
            getRoadNameById(selectedServiceArea.attributes.RoadID)
          }}</el-descriptions-item>
          <el-descriptions-item label="设施">{{
            selectedServiceArea.attributes.Facilities
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="serviceAreaInfoVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 标志牌属性查看对话框 -->
    <el-dialog v-model="signInfoVisible" title="标志牌信息" width="500px">
      <div v-if="selectedSign">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="标志牌类型">{{
            selectedSign.attributes.SignType
          }}</el-descriptions-item>
          <el-descriptions-item label="标志牌内容">{{
            selectedSign.attributes.Content
          }}</el-descriptions-item>
          <el-descriptions-item label="安装日期">{{
            selectedSign.attributes.InstallationDate
          }}</el-descriptions-item>
          <el-descriptions-item label="标牌尺寸">{{
            selectedSign.attributes.BoardSize
          }}</el-descriptions-item>
          <el-descriptions-item label="材料">{{
            selectedSign.attributes.Material
          }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{
            selectedSign.attributes.Status
          }}</el-descriptions-item>
          <el-descriptions-item label="最近检查日期">{{
            selectedSign.attributes.LastInspectionDate
          }}</el-descriptions-item>
          <el-descriptions-item label="所属道路段">{{
            getRoadNameById(selectedSign.attributes.RoadSegmentID)
          }}</el-descriptions-item>
          <el-descriptions-item label="预期寿命"
            >{{ selectedSign.attributes.ExpectedLifespan }} 年</el-descriptions-item
          >
          <el-descriptions-item label="维护日期" v-if="selectedSign.attributes.MaintenanceDate">{{
            selectedSign.attributes.MaintenanceDate
          }}</el-descriptions-item>
          <el-descriptions-item label="维护类型" v-if="selectedSign.attributes.MaintenanceType">{{
            selectedSign.attributes.MaintenanceType
          }}</el-descriptions-item>
          <el-descriptions-item label="描述/维护描述">{{
            selectedSign.attributes.Description
          }}</el-descriptions-item>
          <el-descriptions-item label="标牌照片" v-if="selectedSign.attributes.PhotoBase64">
            <img
              :src="'data:image/jpeg;base64,' + selectedSign.attributes.PhotoBase64"
              style="max-width: 100%; max-height: 200px"
            />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="warning" @click="openReportErrorDialog">上报错误</el-button>
          <el-button @click="signInfoVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 标志牌错误上报对话框 -->
    <el-dialog v-model="reportErrorVisible" title="上报标志牌错误" width="500px">
      <div v-if="selectedSign">
        <el-form
          :model="errorReportForm"
          label-width="120px"
          :rules="errorReportRules"
          ref="errorReportFormRef"
        >
          <el-form-item label="错误类型" prop="errorType">
            <el-select
              v-model="errorReportForm.errorType"
              placeholder="请选择错误类型"
              style="width: 100%"
            >
              <el-option label="内容错误" value="内容错误"></el-option>
              <el-option label="位置错误" value="位置错误"></el-option>
              <el-option label="标牌损坏" value="标牌损坏"></el-option>
              <el-option label="标牌缺失" value="标牌缺失"></el-option>
              <el-option label="其他问题" value="其他问题"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="错误描述" prop="errorDescription">
            <el-input
              v-model="errorReportForm.errorDescription"
              type="textarea"
              rows="4"
              placeholder="请详细描述标志牌的错误情况"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitErrorReport">提交</el-button>
          <el-button @click="reportErrorVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 搜索结果列表对话框 -->
    <el-dialog
      v-model="searchResultVisible"
      title="标志牌搜索结果"
      width="500px"
      :key="refReshSignKey"
    >
      <div v-if="searchResults.length > 0">
        <!-- 使用简单的列表替代表格 -->
        <div class="sign-list">
          <div
            v-for="(item, index) in searchResults"
            :key="index"
            class="sign-item"
            @click="handleSignRowClick(item)"
          >
            <div class="sign-info">
              <div class="sign-type">类型：{{ item.attributes.SignType || '未知' }}</div>
              <div class="sign-content">内容：{{ item.attributes.Content || '无内容' }}</div>
              <div class="sign-status">状态：{{ item.attributes.Status || '未知' }}</div>
            </div>
          </div>
        </div>
      </div>
      <div v-else>
        <el-empty description="未找到匹配的标志牌"></el-empty>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="searchResultVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 风险分析结果对话框 -->
    <el-dialog v-model="analysisResultsVisible" title="标志牌风险分析结果" width="800px">
      <div v-if="riskAnalysisResults.length > 0">
        <h3>分析区域内的标志牌风险评估</h3>

        <!-- 风险分析结果表格 -->
        <el-table :data="riskAnalysisResults" style="width: 100%" @row-click="handleRiskSignClick">
          <el-table-column prop="signType" label="标志牌类型" width="120"></el-table-column>
          <el-table-column prop="content" label="标志牌内容"></el-table-column>
          <el-table-column prop="damagePercent" label="受损程度" width="100">
            <template #default="scope">
              <el-progress
                :percentage="Number(scope.row.damagePercent)"
                :status="getRiskStatus(scope.row.damagePercent)"
              ></el-progress>
            </template>
          </el-table-column>
          <el-table-column prop="riskLevel" label="风险等级" width="100">
            <template #default="scope">
              <el-tag type="danger" v-if="scope.row.riskLevel === '高风险'">{{
                scope.row.riskLevel
              }}</el-tag>
              <el-tag type="warning" v-else-if="scope.row.riskLevel === '中风险'">{{
                scope.row.riskLevel
              }}</el-tag>
              <el-tag type="success" v-else>{{ scope.row.riskLevel }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button type="primary" size="small" @click.stop="viewRiskSignDetail(scope.$index)"
                >查看详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 风险分布图表 -->
        <h4>风险等级分布</h4>
        <div ref="riskChartRef" class="chart-container"></div>
      </div>
      <div v-else>
        <el-empty description="分析区域内未找到标志牌"></el-empty>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="analysisResultsVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 道路标志牌查询结果对话框 -->
    <el-dialog v-model="roadSignsVisible" title="道路标志牌信息" width="800px" :key="roadSignsKey">
      <div v-if="roadSigns.length > 0">
        <h3>{{ selectedRoad?.attributes.RoadName || '当前道路' }}上的标志牌</h3>

        <!-- 标志牌列表 -->
        <div class="road-signs-list">
          <div v-for="(item, index) in roadSigns" :key="index" class="road-sign-item">
            <div class="road-sign-info">
              <div class="road-sign-type">类型：{{ item.attributes.SignType || '未知' }}</div>
              <div class="road-sign-content">内容：{{ item.attributes.Content || '无内容' }}</div>
              <div class="road-sign-status">状态：{{ item.attributes.Status || '未知' }}</div>
              <el-button type="primary" size="small" @click="viewSignDetail(item)"
                >查看详情</el-button
              >
            </div>
          </div>
        </div>

        <!-- 标志牌类型统计图表 -->
        <h4>标志牌类型分布</h4>
        <div ref="signTypeChartRef" class="chart-container"></div>

        <!-- 标志牌状态统计图表 -->
        <h4>标志牌状态分布</h4>
        <div ref="signStatusChartRef" class="chart-container"></div>
      </div>
      <div v-else>
        <el-empty description="该道路上未找到标志牌"></el-empty>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roadSignsVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, ref, reactive } from 'vue'
import { ElForm, ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map.js'
import MapView from '@arcgis/core/views/MapView.js'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import Graphic from '@arcgis/core/Graphic.js'
import Query from '@arcgis/core/rest/support/Query.js'
import SketchViewModel from '@arcgis/core/widgets/Sketch/SketchViewModel.js'
import * as geometryEngine from '@arcgis/core/geometry/geometryEngine.js'
import SimpleFillSymbol from '@arcgis/core/symbols/SimpleFillSymbol.js'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol.js'
import Color from '@arcgis/core/Color.js'
import gaodeLayer from '../utils/GaoDeBaseLayer'
import * as echarts from 'echarts'

let view: MapView | null = null
let highwayLineLayer: FeatureLayer | null = null
let highwayEntryPointLayer: FeatureLayer | null = null
let highwayServiceAreaLayer: FeatureLayer | null = null
let signLayer: FeatureLayer | null = null
let sketchLayer: GraphicsLayer | null = null
let sketchViewModel: SketchViewModel | null = null
let analysisAreaGraphic: Graphic | null = null
let riskSignsGraphics: Graphic[] = []

// 图层可见性控制
const layerVisibility = ref({
  highway: true,
  entryPoint: true,
  serviceArea: true,
  sign: true,
})

// 控制折叠面板的展开状态
const activeCollapse = ref(['layers', 'signSearch', 'riskAnalysis'])
const refReshSignKey = ref(0)

// 查询结果相关
const roadInfoVisible = ref(false)
const entryPointInfoVisible = ref(false)
const serviceAreaInfoVisible = ref(false)
const signInfoVisible = ref(false)
const searchResultVisible = ref(false)
const roadSignsVisible = ref(false)
const reportErrorVisible = ref(false)
const analysisResultsVisible = ref(false)
const isDrawing = ref(false)
let selectedRoad: Graphic | null = null
let selectedEntryPoint: Graphic | null = null
let selectedServiceArea: Graphic | null = null
let selectedSign: Graphic | null = null

// 风险分析相关
const riskAnalysisResults = ref<any[]>([])
const riskChartRef = ref<HTMLElement | null>(null)
let riskChart: echarts.ECharts | null = null

// 错误上报表单相关
const errorReportFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const errorReportForm = reactive({
  errorType: '',
  errorDescription: '',
})
const errorReportRules = {
  errorType: [{ required: true, message: '请选择错误类型', trigger: 'change' }],
  errorDescription: [{ required: true, message: '请输入错误描述', trigger: 'blur' }],
}

// 标志牌搜索相关
const signSearchText = ref('')
// 修改变量定义，将 null 改为空数组作为初始值
let searchResults: Graphic[] = []
let roadSigns: Graphic[] = []
const roadSignsKey = ref(0)

// 图表引用
const signTypeChartRef = ref<HTMLElement | null>(null)
const signStatusChartRef = ref<HTMLElement | null>(null)

// 图表实例
let signTypeChart: echarts.ECharts | null = null
let signStatusChart: echarts.ECharts | null = null

// 将响应式变量改回普通变量
let roadList: Graphic[] = []

// 切换图层可见性
const toggleLayerVisibility = (layerType: string) => {
  switch (layerType) {
    case 'highway':
      if (highwayLineLayer) {
        highwayLineLayer.visible = Boolean(layerVisibility.value.highway)
      }
      break
    case 'entryPoint':
      if (highwayEntryPointLayer) {
        highwayEntryPointLayer.visible = Boolean(layerVisibility.value.entryPoint)
      }
      break
    case 'serviceArea':
      if (highwayServiceAreaLayer) {
        highwayServiceAreaLayer.visible = Boolean(layerVisibility.value.serviceArea)
      }
      break
    case 'sign':
      if (signLayer) {
        signLayer.visible = Boolean(layerVisibility.value.sign)
      }
      break
  }
}

// 根据道路ID获取道路名称
const getRoadNameById = (roadId: string | number) => {
  if (!roadId) return '未知道路'

  const road = roadList.find((road) => road.attributes.FID.toString() === roadId.toString())
  return road ? road.attributes.RoadName : '未知道路'
}

// 搜索标志牌
const searchSignByContent = () => {
  if (!signLayer) {
    ElMessage.warning('标志牌图层未加载')
    return
  }

  if (!signSearchText.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  // 创建查询对象
  const query = new Query()
  query.where = `Content LIKE '%${signSearchText.value}%'`
  // 修改查询字段，确保字段名称与服务器返回的一致
  query.outFields = ['SignType', 'Content', 'Status']
  query.returnGeometry = true

  // 执行查询
  signLayer
    .queryFeatures(query)
    .then((results) => {
      nextTick(() => {
        refReshSignKey.value++
      })
      if (results.features && results.features.length > 0) {
        searchResults = results.features
        console.log('查询结果:', searchResults)
        searchResultVisible.value = true
      } else {
        searchResults = []
        searchResultVisible.value = true
        ElMessage.info('未找到匹配的标志牌')
      }
    })
    .catch((error) => {
      console.error('查询标志牌出错:', error)
      ElMessage.error('查询标志牌失败')
    })
}

// 处理搜索结果行点击
const handleSignRowClick = (row: Graphic) => {
  selectedSign = row
  searchResultVisible.value = false
  signInfoVisible.value = true

  // 如果有地图视图，则定位到该标志牌
  if (view && row.geometry) {
    view.goTo({
      target: row.geometry,
      zoom: 15,
    })
  }
}

// 查询道路上的标志牌
const queryRoadSigns = async () => {
  if (!signLayer || !selectedRoad) {
    ElMessage.warning('标志牌图层未加载或未选择道路')
    return
  }

  try {
    // 创建查询对象
    const query = new Query()
    query.where = `RoadSegmentID = ${selectedRoad.attributes.FID}`
    query.outFields = ['*']
    query.returnGeometry = true

    // 执行查询
    const results = await signLayer.queryFeatures(query)

    nextTick(() => {
      roadSignsKey.value++
    })

    if (results.features && results.features.length > 0) {
      roadSigns = results.features
      roadInfoVisible.value = false
      roadSignsVisible.value = true

      // 初始化图表
      nextTick(() => {
        initRoadSignsCharts()
      })
    } else {
      roadSigns = []
      roadSignsVisible.value = true
      ElMessage.info('该道路上未找到标志牌')
    }
  } catch (error) {
    console.error('查询道路标志牌出错:', error)
    ElMessage.error('查询道路标志牌失败')
  }
}

// 查看标志牌详情
const viewSignDetail = (sign: Graphic) => {
  selectedSign = sign
  roadSignsVisible.value = false
  signInfoVisible.value = true

  // 如果有地图视图，则定位到该标志牌
  if (view && sign.geometry) {
    view.goTo({
      target: sign.geometry,
      zoom: 15,
    })
  }
}

// 打开错误上报对话框
const openReportErrorDialog = () => {
  if (!selectedSign) return

  // 重置表单
  errorReportForm.errorType = ''
  errorReportForm.errorDescription = ''

  // 显示错误上报对话框
  signInfoVisible.value = false
  reportErrorVisible.value = true
}

// 提交错误上报
const submitErrorReport = async () => {
  if (!errorReportFormRef.value || !selectedSign || !signLayer) return

  await errorReportFormRef.value.validate(async (valid: any) => {
    if (valid) {
      try {
        // 创建更新后的标志牌图形
        const updatedSign = selectedSign!.clone()

        // 更新状态为"待维修"
        updatedSign.attributes.Status = '待维修'

        // 更新描述，添加错误报告信息
        const currentDate = new Date().toISOString().split('T')[0]
        const errorReport = `[${currentDate}] 错误类型: ${errorReportForm.errorType}, 描述: ${errorReportForm.errorDescription}`

        // 如果已有描述，则添加到现有描述后面
        if (updatedSign.attributes.Description) {
          updatedSign.attributes.Description =
            updatedSign.attributes.Description + '\n\n' + errorReport
        } else {
          updatedSign.attributes.Description = errorReport
        }

        // 应用编辑
        const result = await signLayer?.applyEdits({
          updateFeatures: [updatedSign],
        })

        if (result!.updateFeatureResults.length > 0) {
          ElMessage.success('标志牌错误已成功上报')
          reportErrorVisible.value = false

          // 更新本地的selectedSign对象，以便在界面上显示更新后的信息
          selectedSign = updatedSign
          signInfoVisible.value = true
        } else {
          ElMessage.error('标志牌错误上报失败')
        }
      } catch (error) {
        console.error('上报标志牌错误出错:', error)
        ElMessage.error('标志牌错误上报失败')
      }
    }
  })
}

// 初始化道路标志牌图表
const initRoadSignsCharts = () => {
  loadSignTypeDistribution()
  loadSignStatusDistribution()
}

// 加载标志牌类型分布数据
const loadSignTypeDistribution = () => {
  if (!signTypeChartRef.value || roadSigns.length === 0) return

  // 统计各类型标志牌数量
  const typeCount: Record<string, number> = {}
  roadSigns.forEach((sign) => {
    const signType = sign.attributes.SignType
    if (signType) {
      typeCount[signType] = (typeCount[signType] || 0) + 1
    }
  })

  // 准备图表数据
  const chartData = Object.entries(typeCount).map(([name, value]) => ({ name, value }))

  // 初始化图表
  if (!signTypeChart) {
    signTypeChart = echarts.init(signTypeChartRef.value)
  } else {
    signTypeChart.dispose()
    signTypeChart = echarts.init(signTypeChartRef.value)
  }

  // 设置图表选项
  signTypeChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: chartData.map((item) => item.name),
    },
    series: [
      {
        name: '标志牌类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: chartData,
      },
    ],
  })
}

// 加载标志牌状态分布数据
const loadSignStatusDistribution = () => {
  if (!signStatusChartRef.value || roadSigns.length === 0) return

  // 统计各状态标志牌数量
  const statusCount: Record<string, number> = {}
  roadSigns.forEach((sign) => {
    const status = sign.attributes.Status
    if (status) {
      statusCount[status] = (statusCount[status] || 0) + 1
    }
  })

  // 准备图表数据
  const chartData = Object.entries(statusCount).map(([name, value]) => ({ name, value }))

  // 初始化图表
  if (!signStatusChart) {
    signStatusChart = echarts.init(signStatusChartRef.value)
  } else {
    signStatusChart.dispose()
    signStatusChart = echarts.init(signStatusChartRef.value)
  }

  // 设置图表选项
  signStatusChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: chartData.map((item) => item.name),
    },
    series: [
      {
        name: '标志牌状态',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: chartData,
      },
    ],
  })
}

// 加载道路列表
const loadRoadList = () => {
  // 创建高速公路线图层
  const tempHighwayLineLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/3',
    outFields: ['FID', 'RoadName'],
    visible: false,
  })

  // 查询所有道路
  const query = tempHighwayLineLayer.createQuery()
  query.outFields = ['FID', 'RoadName']
  query.returnGeometry = false

  tempHighwayLineLayer
    .queryFeatures(query)
    .then((results) => {
      if (results.features && results.features.length > 0) {
        roadList = results.features
      }
    })
    .catch((error) => {
      console.error('加载道路列表出错:', error)
      ElMessage.error('加载道路列表失败')
    })
}

// 开始绘制分析区域
const startDrawAnalysisArea = () => {
  if (!view) return

  // 清除之前的分析结果
  clearAnalysis()

  // 创建绘图图层（如果不存在）
  if (!sketchLayer) {
    sketchLayer = new GraphicsLayer({
      title: '绘图图层',
    })
    view.map.add(sketchLayer)
  }

  // 创建绘图工具（如果不存在）
  if (!sketchViewModel) {
    sketchViewModel = new SketchViewModel({
      view: view,
      layer: sketchLayer,
      polygonSymbol: new SimpleFillSymbol({
        color: new Color([255, 255, 0, 0.2]),
        outline: {
          color: new Color([255, 255, 0, 0.8]),
          width: 2,
        },
      }),
    })

    // 监听绘图完成事件
    sketchViewModel.on('create', (event) => {
      if (event.state === 'complete') {
        analysisAreaGraphic = event.graphic
        isDrawing.value = false
        ElMessage.success('分析区域绘制完成，可以执行风险分析')
      }
    })
  }

  isDrawing.value = true
  ElMessage.info('请在地图上绘制分析区域')

  // 开始绘制多边形
  sketchViewModel.create('polygon')
}

// 执行风险分析
const performRiskAnalysis = async () => {
  if (!signLayer || !analysisAreaGraphic) {
    ElMessage.warning('请先绘制分析区域')
    return
  }

  try {
    // 创建查询对象
    const query = new Query()
    query.geometry = analysisAreaGraphic.geometry
    query.spatialRelationship = 'intersects'
    query.outFields = ['*']
    query.returnGeometry = true

    // 执行查询
    const results = await signLayer.queryFeatures(query)

    if (results.features && results.features.length > 0) {
      // 保存原始的Graphic对象
      riskSignsGraphics = results.features

      // 转换为普通JavaScript对象用于模板渲染
      riskAnalysisResults.value = results.features.map((feature) => {
        const damagePercent = Number(feature.attributes.DamagePercent || 0)
        let riskLevel = '低风险'

        if (damagePercent >= 75) {
          riskLevel = '高风险'
        } else if (damagePercent >= 50) {
          riskLevel = '中风险'
        }

        return {
          signType: feature.attributes.SignType || '',
          content: feature.attributes.Content || '',
          damagePercent: damagePercent,
          riskLevel: riskLevel,
          status: feature.attributes.Status || '',
          installationDate: feature.attributes.InstallationDate || '',
          lastInspectionDate: feature.attributes.LastInspectionDate || '',
          description: feature.attributes.Description || '',
        }
      })

      // 显示分析结果
      analysisResultsVisible.value = true

      // 初始化风险分布图表
      nextTick(() => {
        initRiskChart()
      })
    } else {
      riskSignsGraphics = []
      riskAnalysisResults.value = []
      ElMessage.info('分析区域内未找到标志牌')
      analysisResultsVisible.value = true
    }
  } catch (error) {
    console.error('执行风险分析出错:', error)
    ElMessage.error('风险分析失败')
  }
}

// 清除分析
const clearAnalysis = () => {
  if (sketchLayer) {
    sketchLayer.removeAll()
  }

  analysisAreaGraphic = null
  riskSignsGraphics = []
  riskAnalysisResults.value = []
  analysisResultsVisible.value = false

  // 销毁图表实例
  if (riskChart) {
    riskChart.dispose()
    riskChart = null
  }
}

// 初始化风险分布图表
const initRiskChart = () => {
  if (!riskChartRef.value || riskAnalysisResults.value.length === 0) return

  // 统计各风险等级标志牌数量
  const riskCount = {
    高风险: 0,
    中风险: 0,
    低风险: 0,
  }

  riskAnalysisResults.value.forEach((sign) => {
    riskCount[sign.riskLevel as keyof typeof riskCount]++
  })

  // 准备图表数据
  const chartData = Object.entries(riskCount).map(([name, value]) => ({ name, value }))

  // 初始化图表
  if (!riskChart) {
    riskChart = echarts.init(riskChartRef.value)
  } else {
    riskChart.dispose()
    riskChart = echarts.init(riskChartRef.value)
  }

  // 设置图表选项
  riskChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: chartData.map((item) => item.name),
    },
    series: [
      {
        name: '风险等级',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: chartData,
        color: ['#F56C6C', '#E6A23C', '#67C23A'], // 红色、黄色、绿色
      },
    ],
  })
}

// 处理风险分析结果行点击
const handleRiskSignClick = (row: any) => {
  // 获取对应的原始Graphic对象
  const graphicIndex = riskAnalysisResults.value.indexOf(row)
  if (graphicIndex >= 0 && graphicIndex < riskSignsGraphics.length) {
    const graphic = riskSignsGraphics[graphicIndex]

    // 如果有地图视图，则定位到该标志牌
    if (view && graphic.geometry) {
      view.goTo({
        target: graphic.geometry,
        zoom: 15,
      })
    }
  }
}

// 查看风险标志牌详情
const viewRiskSignDetail = (index: number) => {
  if (index >= 0 && index < riskSignsGraphics.length) {
    selectedSign = riskSignsGraphics[index]
    analysisResultsVisible.value = false
    signInfoVisible.value = true

    // 如果有地图视图，则定位到该标志牌
    if (view && selectedSign.geometry) {
      view.goTo({
        target: selectedSign.geometry,
        zoom: 15,
      })
    }
  }
}

// 根据受损程度获取状态
const getRiskStatus = (damagePercent: string | number) => {
  const percent = Number(damagePercent || 0)
  if (percent >= 75) return 'exception' // 红色
  if (percent >= 50) return 'warning' // 黄色
  return 'success' // 绿色
}

// 初始化地图
onMounted(() => {
  // 创建高速公路线图层
  highwayLineLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/3',
    title: '高速公路',
    visible: Boolean(layerVisibility.value.highway),
    outFields: ['*'], // 确保所有字段都可用
    popupEnabled: false, // 禁用默认弹出窗口，使用自定义弹窗
  })

  // 创建高速公路进入点图层
  highwayEntryPointLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/0',
    title: '高速公路进入点',
    visible: Boolean(layerVisibility.value.entryPoint),
    outFields: ['*'],
    popupEnabled: false,
  })

  // 创建高速公路服务区图层
  highwayServiceAreaLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/1',
    title: '高速公路服务区',
    visible: Boolean(layerVisibility.value.serviceArea),
    outFields: ['*'],
    popupEnabled: false,
  })

  // 创建标志牌图层
  signLayer = new FeatureLayer({
    url: 'https://services6.arcgis.com/aSAH0FbO8tv30xLs/arcgis/rest/services/HighwayManagementSystem/FeatureServer/2',
    title: '标志牌',
    visible: Boolean(layerVisibility.value.sign),
    outFields: ['*'],
    popupEnabled: false,
  })

  // 创建地图实例
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
    layers: [highwayLineLayer, highwayEntryPointLayer, highwayServiceAreaLayer, signLayer], // 添加图层到地图
  })

  // 创建地图视图
  view = new MapView({
    container: 'mapView',
    map: map,
    zoom: 10,
    center: [116.7461293, 36.5598627], // 默认中心点（北京）
  })

  // 监听点击事件，用于查询要素信息
  view.on('click', async function (event) {
    // 转换空间参考
    const mapPoint = event.mapPoint
    // 创建查询对象
    const query = new Query()
    query.geometry = mapPoint
    query.distance = 1 // 增加点击容差
    query.units = 'miles'
    query.spatialRelationship = 'intersects'
    query.returnGeometry = true
    query.outFields = ['*']

    try {
      // 查询高速公路图层
      if (highwayLineLayer && highwayLineLayer.visible) {
        const roadResult = await highwayLineLayer.queryFeatures(query)
        if (roadResult.features.length > 0) {
          // 找到道路，显示信息
          selectedRoad = roadResult.features[0]
          roadInfoVisible.value = true
          return
        }
      }

      // 查询高速公路进入点图层
      if (highwayEntryPointLayer && highwayEntryPointLayer.visible) {
        const entryPointResult = await highwayEntryPointLayer.queryFeatures(query)
        if (entryPointResult.features.length > 0) {
          // 找到进入点，显示信息
          selectedEntryPoint = entryPointResult.features[0]
          entryPointInfoVisible.value = true
          return
        }
      }

      // 查询高速公路服务区图层
      if (highwayServiceAreaLayer && highwayServiceAreaLayer.visible) {
        const serviceAreaResult = await highwayServiceAreaLayer.queryFeatures(query)
        if (serviceAreaResult.features.length > 0) {
          // 找到服务区，显示信息
          selectedServiceArea = serviceAreaResult.features[0]
          serviceAreaInfoVisible.value = true
          return
        }
      }

      // 查询标志牌图层
      if (signLayer && signLayer.visible) {
        const signResult = await signLayer.queryFeatures(query)
        if (signResult.features.length > 0) {
          // 找到标志牌，显示信息
          selectedSign = signResult.features[0]
          signInfoVisible.value = true
          return
        }
      }
    } catch (error) {
      console.error('查询要素出错:', error)
      ElMessage.error('查询要素失败')
    }
  })

  // 加载道路列表
  loadRoadList()
})

// 窗口大小变化时重新调整图表大小
const resizeCharts = () => {
  signTypeChart?.resize()
  signStatusChart?.resize()
  riskChart?.resize()
}

// 组件卸载时清理资源
onUnmounted(() => {
  if (view) {
    view = null
  }

  // 移除窗口大小变化监听
  window.removeEventListener('resize', resizeCharts)

  // 销毁图表实例
  signTypeChart?.dispose()
  signStatusChart?.dispose()
  riskChart?.dispose()

  // 清理绘图资源
  if (sketchViewModel) {
    sketchViewModel.destroy()
    sketchViewModel = null
  }

  // 清理分析资源
  analysisAreaGraphic = null
  riskSignsGraphics = []
})

// 添加窗口大小变化监听
onMounted(() => {
  window.addEventListener('resize', resizeCharts)
})
</script>

<style scoped>
.map-view {
  width: 100%;
  height: 100%;
  position: relative;
}

.layer-control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
  width: 280px;
}

.layer-card {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 添加标志牌列表样式 */
.sign-list,
.road-signs-list {
  max-height: 400px;
  overflow-y: auto;
}

.sign-item,
.road-sign-item {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.sign-item:hover,
.road-sign-item:hover {
  background-color: #f5f7fa;
}

.sign-item:last-child,
.road-sign-item:last-child {
  border-bottom: none;
}

.sign-info,
.road-sign-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.road-sign-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  position: relative;
}

.road-sign-info .el-button {
  align-self: flex-end;
  margin-top: 8px;
}

.sign-type,
.road-sign-type {
  font-weight: bold;
  color: #303133;
}

.sign-content,
.road-sign-content {
  color: #606266;
}

.sign-status,
.road-sign-status {
  color: #909399;
  font-size: 0.9em;
}

/* 图表容器样式 */
.chart-container {
  height: 300px;
  width: 100%;
  margin: 20px 0;
}

h3,
h4 {
  margin: 15px 0;
  color: #303133;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .layer-control-panel {
    width: 220px;
    top: 10px;
    right: 10px;
  }
}
</style>
